package com.glodon.paas.document.storage.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glodon.paas.document.storage.Storage;
import com.glodon.paas.document.storage.StoreException;
import com.glodon.paas.document.storage.dao.StorageDAO;
import com.glodon.paas.document.storage.directory.Directory;
import com.glodon.paas.document.storage.model.Store;

@Service
public class StorageService {
    @Autowired
    private StorageDAO storageDAO;
    private Map<String, Directory> directories = new HashMap<String, Directory>();

    public void setStorageDAO(StorageDAO storageDAO) {
        this.storageDAO = storageDAO;
    }

    public void createStorage(String name, String directory) throws StoreException {
        if (directories.get(directory) == null)
            throw new StoreException("directory is not exists, name = " + directory);
        storageDAO.addStorage(name, directory);
    }

    public List<Storage> getStorages() {
        List<Store> stores = storageDAO.getStores();
        List<Storage> storages = new ArrayList<Storage>();
        for (Store store : stores) {
            storages.add(createStorage(store));
        }
        return storages;
    }

    private Storage createStorage(Store store) {
        Storage storage = new Storage();
        storage.setStorageDAO(storageDAO);
        storage.setDirectory(directories.get(store.getDirectory()));
        storage.setName(store.getName());
        return storage;
    }

    public void registry(String name, Directory directory) {
        directories.put(name, directory);
    }

    public Storage getStorage(String name) {
        return createStorage(storageDAO.getStoreByName(name));
    }
}
